package com.supercube.system.controller;

import com.github.pagehelper.PageInfo;
import com.supercube.common.annotation.Log;
import com.supercube.common.config.Constant;
import com.supercube.common.controller.BaseController;
import com.supercube.common.domain.Tree;
import com.supercube.common.service.DictService;
import com.supercube.common.utils.*;
import com.supercube.sport.yoga.utils.ResultInfo;
import com.supercube.system.domain.DeptDO;
import com.supercube.system.domain.RoleDO;
import com.supercube.system.domain.UserDO;
import com.supercube.system.service.RoleService;
import com.supercube.system.service.UserService;
import com.supercube.system.vo.UserBO;
import com.supercube.system.vo.UserVO;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequestMapping("/sys/user")
@RestController
public class UserController extends BaseController {
    private String prefix = "system/user";
    @Autowired
    UserService userService;
    @Autowired
    RoleService roleService;
    @Autowired
    DictService dictService;

    //@RequiresPermissions("sys:user:user")
    @GetMapping("")
    String user(Model model) {
        return prefix + "/user";
    }

    @PostMapping("/queryUserlist")
    @ResponseBody
    ResultInfo list(@RequestBody UserBO bo) {
        // 查询列表数据
        List<UserDO> sysUserList = userService.queryUsrlist(bo);
        PageInfo<UserDO> pageInfo = new PageInfo<>(sysUserList);
        return ResultInfo.success(pageInfo);
    }

    @GetMapping("/queryRoleMenuByRoleId")
    @ResponseBody
    ResultInfo list(@RequestParam("roleId") String roleId) {
        // 查询列表数据
        List<String> list = userService.queryRoleMenu("",roleId);
        return ResultInfo.success(list);
    }



    @PostMapping("/queryCoachAndSaleList")
    @ResponseBody
    @ApiOperation(value = "查询销售与教练",notes = "查询销售与教练，empType=2:教练；empType=null:为销售")
    ResultInfo queryCoachAndSaleList(@RequestBody UserBO bo) {
        // 查询列表数据
        List<UserDO> sysUserList = userService.queryCoachAndSaleList(bo);
        PageInfo<UserDO> pageInfo = new PageInfo<>(sysUserList);
        return ResultInfo.success(pageInfo);
    }

    @PostMapping("/queryCoachAndSale")
    @ResponseBody
    @ApiOperation(value = "查询销售与教练不带分页",notes = "查询销售与教练，empType=2:教练；empType=null:为销售")
    ResultInfo queryCoachAndSale(@RequestBody UserBO bo) {
        // 查询列表数据
        bo.setPageNum(null);
        bo.setPageSize(null);
        List<UserDO> sysUserList = userService.queryCoachAndSale(bo);
        return ResultInfo.success(sysUserList);
    }

    @GetMapping("/list")
    @ResponseBody
    PageUtils list(@RequestParam Map<String, Object> params) {
        // 查询列表数据
        Query query = new Query(params);
        List<UserDO> sysUserList = userService.list(query);
        int total = userService.count(query);
        PageUtils pageUtil = new PageUtils(sysUserList, total);
        return pageUtil;
    }

//    @RequiresPermissions("sys:user:add")
    @Log("添加用户")
    @GetMapping("/add")
    String add(Model model) {
        List<RoleDO> roles = roleService.list();
        model.addAttribute("roles", roles);
        return prefix + "/add";
    }

//    @RequiresPermissions("sys:user:edit")
    @Log("编辑用户")
    @GetMapping("/edit/{id}")
    ResultInfo edit( @PathVariable("id") Long id) {
        Map map = new HashMap();
        UserDO userDO = userService.get(id);
        map.put("user", userDO);
        List<RoleDO> roles = roleService.list(id);
        map.put("roles", roles);
        return ResultInfo.success(map);
    }

    //@RequiresPermissions("sys:user:add")
    @Log("保存用户")
    @PostMapping("/save")
    @ResponseBody
    @ApiOperation(value = "保存用户",notes = "保存用户")
    ResultInfo save(@RequestBody UserDO user) {
        user.setPassword(MD5Utils.encrypt(user.getUsername(), "111111"));
        int save = userService.save(user);
        if (save > 0) {
            return ResultInfo.success("保存成功");
        } else if (save == -1) {
            return ResultInfo.failed("手机号已存在");
        }
        return ResultInfo.failed("保存失败");
    }

    //@RequiresPermissions("sys:user:edit")
    @Log("更新用户")
    @PostMapping("/update")
    @ResponseBody
    @ApiOperation(value = "更新用户",notes = "更新用户")
    ResultInfo update(@RequestBody UserDO user) {
        UserDO userDO = userService.get(user.getUserId());
        if (userDO == null) {
            return ResultInfo.failed("修改的用户不存在");
        }
        String allowLogin = user.getAllowLogin();
        if ("1".equals(allowLogin) && StringUtils.isEmpty(userDO.getPassword())) {
            user.setPassword(MD5Utils.encrypt(user.getUsername(), "111111"));
        } else {
            user.setPassword(userDO.getPassword());
        }
        if (userService.update(user) > 0) {
            return ResultInfo.success("更新成功");
        }
        return ResultInfo.failed("更新失败");
    }


    //@RequiresPermissions("sys:user:edit")
    @Log("更新个人信息")
    @PostMapping("/updatePersonal")
    @ResponseBody
    @ApiOperation(value = "更新个人信息",notes = "更新个人信息")
    ResultInfo updatePersonal(@RequestBody UserDO user) {
        if (userService.updatePersonal(user) > 0) {
            return ResultInfo.success("更新成功");
        }
        return ResultInfo.failed("更新失败");
    }


    //@RequiresPermissions("sys:user:remove")
    @Log("删除用户")
    @PostMapping("/remove")
    @ResponseBody
    @ApiOperation(value = "删除用户",notes = "删除用户")
    ResultInfo remove(@RequestParam("id")Long id) {
        if (userService.remove(id) > 0) {
            return ResultInfo.success("删除成功");
        }
        return ResultInfo.failed("删除失败");
    }

    //@RequiresPermissions("sys:user:batchRemove")
    @Log("批量删除用户")
    @PostMapping("/batchRemove")
    @ResponseBody
    @ApiOperation(value = "批量删除用户",notes = "批量删除用户")
    ResultInfo batchRemove(@RequestBody Long[] userIds) {
        if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
            return ResultInfo.failed("演示系统不允许修改,完整体验请部署程序");
        }
        int r = userService.batchremove(userIds);
        if (r > 0) {
            return ResultInfo.success("批量删除成功");
        }
        return ResultInfo.failed("删除失败");
    }

    @PostMapping("/exit")
    @ResponseBody
    boolean exit(@RequestParam Map<String, Object> params) {
        // 存在，不通过，false
        return !userService.exit(params);
    }

    //@RequiresPermissions("sys:user:resetPwd")
    @Log("请求更改用户密码")
    @GetMapping("/resetPwd/{id}")
    String resetPwd(@PathVariable("id") Long userId, Model model) {

        UserDO userDO = new UserDO();
        userDO.setUserId(userId);
        model.addAttribute("user", userDO);
        return prefix + "/reset_pwd";
    }

    @Log("提交更改用户密码")
    @ApiOperation(value = "提交更改用户密码", notes = "提交更改用户密码")
    @PostMapping("/resetPwd")
    @ResponseBody
    ResultInfo resetPwd(@RequestBody UserVO userVO) {
        if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
            return ResultInfo.failed("演示系统不允许修改,完整体验请部署程序");
        }
        try {
            userService.resetPwd(userVO, getUser());
            return ResultInfo.success("密码重置成功");
        } catch (Exception e) {
            e.printStackTrace();
            return ResultInfo.failed("密码重置失败");
        }
    }
    @Log("批量更改用户密码")
    @ApiOperation(value = "批量更改用户密码", notes = "批量更改用户密码")
    @PostMapping("/batchResetPwd")
    @ResponseBody
    ResultInfo batchResetPwd(@RequestBody Long[] userIds) {
        try {
            userService.batchResetPwd(userIds);
            return ResultInfo.success("密码重置成功");
        } catch (Exception e) {
            e.printStackTrace();
            return ResultInfo.failed("密码重置失败");
        }
    }
    //@RequiresPermissions("sys:user:resetPwd")
    @Log("admin提交更改用户密码")
    @PostMapping("/adminResetPwd")
    @ResponseBody
    R adminResetPwd(UserVO userVO) {
        if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
            return R.error(1, "演示系统不允许修改,完整体验请部署程序");
        }
        try {
            userService.adminResetPwd(userVO);
            return R.ok();
        } catch (Exception e) {
            return R.error(1, e.getMessage());
        }

    }

    @GetMapping("/tree")
    @ResponseBody
    public Tree<DeptDO> tree() {
        Tree<DeptDO> tree = new Tree<DeptDO>();
        tree = userService.getTree();
        return tree;
    }

    @GetMapping("/treeView")
    String treeView() {
        return prefix + "/userTree";
    }

    @GetMapping("/personal")
    String personal(Model model) {
        UserDO userDO = userService.get(getUserId());
        model.addAttribute("user", userDO);
        model.addAttribute("hobbyList", dictService.getHobbyList(userDO));
        model.addAttribute("sexList", dictService.getSexList());
        return prefix + "/personal";
    }

    @ResponseBody
    @PostMapping("/uploadImg")
    R uploadImg(@RequestParam("avatar_file") MultipartFile file, String avatar_data, HttpServletRequest request) {
        if ("test".equals(getUsername())) {
            return R.error(1, "演示系统不允许修改,完整体验请部署程序");
        }
        Map<String, Object> result = new HashMap<>();
        try {
            result = userService.updatePersonalImg(file, avatar_data, getUserId());
        } catch (Exception e) {
            return R.error("更新图像失败！");
        }
        if (result != null && result.size() > 0) {
            return R.ok(result);
        } else {
            return R.error("更新图像失败！");
        }
    }
}
